package net.hpxn.gsmc.core.server;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.hpxn.gsmc.config.server.ServerConfigs.ServerConfig;
import net.hpxn.gsmc.core.server.exceptions.ServerCommunicationException;
import net.hpxn.gsmc.core.server.exceptions.ServerUnavailableException;

public class L4DServer extends SourceServer {

	public L4DServer( ServerConfig pServerConfig ) {
		super( pServerConfig );
	}

	@Override
	public void updateServerStatus() throws ServerUnavailableException {
		String wRawServerStatus = null;
		try {
			wRawServerStatus = getServerStatus();
		} catch ( ServerCommunicationException e ) {
			throw new ServerUnavailableException( e );
		}
		
		if ( wRawServerStatus != null ) {
			String[] wStatusLines = wRawServerStatus.split( "\n" );

			if ( wStatusLines != null && wStatusLines.length > 0 ) {
				try {
					setHostname( parseHostname( wStatusLines[ 0 ] ) );
					setVersion( parseVersion( wStatusLines[ 1 ] ) );
					setMapName( parseMapName( wStatusLines[ 4 ] ) );
					setPlayerCount( parsePlayerCount( wStatusLines[ 5 ] ) );
					setMaxPlayers( parseMaxPlayers( wStatusLines[ 5 ] ) );
				} catch ( Exception e ) {
					throw new ServerUnavailableException( e );
				}
			}
		}
	}
	
	protected int parseMaxPlayers( String pStatusLine ) {
		Pattern wPattern = Pattern
				.compile( "players : (\\d+) humans, (\\d+) bots \\((\\d+) max\\) \\((.*?)\\) \\((.*?)\\)" );
		Matcher wMatcher = wPattern.matcher( pStatusLine );

		if ( wMatcher.lookingAt() ) {
			return Integer.parseInt( wMatcher.group( 3 ) );
		}

		return 0;
	}
	
	protected int parsePlayerCount( String pStatusLine ) {
		Pattern wPattern = Pattern
				.compile( "players : (\\d+) humans, (\\d+) bots \\((\\d+) max\\) \\((.*?)\\) \\((.*?)\\)" );
		Matcher wMatcher = wPattern.matcher( pStatusLine );

		if ( wMatcher.lookingAt() ) {
			return Integer.parseInt( wMatcher.group( 1 ) );
		}

		return 0;
	}
	
	protected String parseHostname( String pStatusLine ) {
		return pStatusLine.split( ":" )[ 1 ].trim();
	}

	protected String parseVersion( String pStatusLine ) {
		return pStatusLine.split( ":" )[ 1 ].trim();
	}

	protected String parseMapName( String pStatusLine ) {
		return pStatusLine.split( ":" )[ 1 ].trim().split( " " )[ 0 ];
	}
}